package com.inplaceedit.shared.webservice.impl;

import java.util.ArrayList;
import java.util.List;

import com.google.gwt.core.client.Scheduler;
import com.google.gwt.core.client.Scheduler.ScheduledCommand;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.inplaceedit.shared.dto.CompanyDto;
import com.inplaceedit.shared.webservice.CompanyRemoteServiceAsync;
import com.inplaceedit.shared.webservice.impl.data.Company;
import com.inplaceedit.shared.webservice.impl.data.Data;

public class CompanyRemoteServiceImpl implements CompanyRemoteServiceAsync {
	@Override
	public void get(final String id, final AsyncCallback<CompanyDto> callback) {
		Scheduler.get().scheduleDeferred(new ScheduledCommand() {
			@Override
			public void execute() {
				try {
					callback.onSuccess(Converter.convert(Data.get().getCompany(
							id)));
				} catch (final Throwable e) {
					callback.onFailure(e);
				}
			}
		});
	}

	@Override
	public void list(final AsyncCallback<List<CompanyDto>> callback) {
		Scheduler.get().scheduleDeferred(new ScheduledCommand() {
			@Override
			public void execute() {
				try {
					callback.onSuccess(convert(Data.get().getCompanyList()));
				} catch (final Throwable e) {
					callback.onFailure(e);
				}
			}
		});
	}

	@Override
	public void save(final CompanyDto object,
			final AsyncCallback<CompanyDto> callback) {
		Scheduler.get().scheduleDeferred(new ScheduledCommand() {
			@Override
			public void execute() {
				try {
					callback.onSuccess(Converter.convert(Data.get()
							.saveCompany(Converter.convert(object))));
				} catch (final Throwable e) {
					callback.onFailure(e);
				}
			}
		});
	}

	private List<CompanyDto> convert(final List<Company> from) {
		final List<CompanyDto> to = new ArrayList<CompanyDto>();
		for (final Company item : from) {
			to.add(Converter.convert(item));
		}
		return to;
	}
}
